/**
 *
 * @param {*} reducer 处理函数
 * @param {*} preloadState 初始状态
 */

export default function createStore(reducer, preloadState) {
  let state = preloadState; //仓库中的状态
  let currentListeners = [];

  function getState() {
    return state;
  }
  function subscribe(listener) {
    currentListeners.push(listener);
    //返回一个取消订阅
    return function(){
      let index = currentListeners.indexOf(listener);
      currentListeners.splice(index,1);//删掉此监听函数
    }
  }
  function dispatch(action) {
    state = reducer(state, action);
    currentListeners.forEach((l) => l());
    return action;
  }
  dispatch({type: '@@redux/init'});
  return {
    getState, // 获取当前状态
    dispatch,
    subscribe,
  };
}
